<template>
  <div class="nest_item">
    <!--视频-->
    <div ref="ref_wrap" class="nest_video">
      <div :id="geneIdByUrl()" style="width: 100%; height: 100%" />
    </div>
    <!--天气-->
    <div v-if="true" class="nest_weather">
      <div class="weather_item">
        <svg-icon
          v-if="weatherInfo.wind_speed < 6"
          class="weather_icon"
          icon-class="wind_normal"
        />
        <svg-icon v-else class="weather_icon" icon-class="wind_warning" />
        <div class="weather_value">
          {{ weatherInfo.wind_speed }}
          <span class="weather_key">m/s</span>
        </div>
        <div class="weather_key">
          风速{{ getWindLevel(weatherInfo.wind_force) }}级
        </div>
      </div>
      <div class="weather_item" style="margin: 8px 0">
        <svg-icon
          v-if="weatherInfo.weather_detection === '无雨雪'"
          class="weather_icon"
          icon-class="rain_normal"
        />
        <svg-icon v-else class="weather_icon" icon-class="rain_warning" />
        <div class="weather_value">{{ weatherInfo.weather_detection }}</div>
        <div class="weather_key">雨雪</div>
      </div>
      <div class="weather_item">
        <svg-icon class="weather_icon" icon-class="humidity" />
        <div class="weather_value">
          {{ weatherInfo.humidity }}%<span class="weather_key">RH</span>
        </div>
        <div class="weather_key">湿度</div>
      </div>
    </div>
    <!--标题-->
    <div v-if="true" class="bottom_info">
      <div class="title">{{ videoName }}</div>
      <el-dropdown
        v-if="isFlying && isDJ"
        placement="top"
        @command="handleCommand"
      >
        <span class="el-dropdown-link">{{ currentQuality.name }}</span>
        <el-dropdown-menu slot="dropdown" class="quality-menu">
          <el-dropdown-item
            class="quality-item"
            :command="qualityList[0]"
            :class="
              currentQuality.id === qualityList[0].id ? 'selected-item' : ''
            "
          >
            {{ qualityList[0].name }}
          </el-dropdown-item>
          <el-dropdown-item
            class="quality-item"
            :command="qualityList[1]"
            :class="
              currentQuality.id === qualityList[1].id ? 'selected-item' : ''
            "
          >
            {{ qualityList[1].name }}
          </el-dropdown-item>
          <el-dropdown-item
            class="quality-item"
            :command="qualityList[2]"
            :class="
              currentQuality.id === qualityList[2].id ? 'selected-item' : ''
            "
          >
            {{ qualityList[2].name }}
          </el-dropdown-item>
          <el-dropdown-item
            class="quality-item"
            :command="qualityList[3]"
            :class="
              currentQuality.id === qualityList[3].id ? 'selected-item' : ''
            "
          >
            {{ qualityList[3].name }}
          </el-dropdown-item>
          <el-dropdown-item
            class="quality-item"
            :class="
              currentQuality.id === qualityList[4].id ? 'selected-item' : ''
            "
            :command="qualityList[4]"
          >
            {{ qualityList[4].name }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <svg-icon
        v-if="isFlying"
        class="btn_enter"
        icon-class="share-square-o"
        @click="showShareForm()"
      />
      <svg-icon class="btn_enter" icon-class="enter" @click="enterNestInfo()" />
    </div>
  </div>
</template>

<script>
import AgoraRTC from "agora-rtc-sdk-ng";

import { djiAgoraToken } from "@/api/kanban";

const CNWord = [
  "零",
  "一",
  "二",
  "三",
  "四",
  "五",
  "六",
  "七",
  "八",
  "九",
  "十",
  "十一",
  "十二",
  "十三",
  "十四",
  "十五",
  "十六",
  "十七",
];

const QUALITY_LIST = [
  {
    id: "0",
    name: "智能",
  },
  {
    id: "1",
    name: "流畅",
  },
  {
    id: "2",
    name: "标清",
  },
  {
    id: "3",
    name: "高清",
  },
  {
    id: "4",
    name: "超清",
  },
];

export default {
  name: "VideoComp",
  props: {
    videoUrl: {
      type: String,
      default: () => "",
    },
    isFlying: {
      type: Boolean,
      default: () => false,
    },
    isDJ: {
      type: Boolean,
      default: () => true,
    },
    videoName: {
      type: String,
      default: () => "",
    },
    nestInfo: {
      type: Object,
      default: () => null,
    },
    autoPlay: {
      type: Boolean,
      default: () => true,
    },
    // weatherInfo: {
    //   type: Object,
    //   default: () => {
    //     return {
    //       humidity: "N",
    //       weather_detection: "未知",
    //       wind_force: "N",
    //       wind_speed: "N",
    //     };
    //   },
    // },
  },
  data() {
    return {
      canvasId: "",
      aliPlayer: "",
      intervalTask: "",
      rtcClient: null,
      rtcToken: null,
      rtcChannel: null,
      //
      currentQuality: QUALITY_LIST[0],
      qualityId: "0",
      qualityList: QUALITY_LIST,
      playerType: 0,
      player: null,
      timeoutId: null,
      is_offline_2: false,

      weatherInfo: {
        humidity: "N",
        weather_detection: "未知",
        wind_force: "N",
        wind_speed: "N",
      },
    };
  },
  mounted() {
    console.log("mounted url", this.videoUrl, this.nestInfo);
    if (this.autoPlay) {
      this.initPlayer();
    }
    this.initBus();
  },
  beforeDestroy() {
    this.releasePlayer();
    this.removeBus();
  },
  methods: {
    initBus() {
      let that = this;
      that.$bus.on("nestWeatherUpdate", (res) => {
        let findNest = null;
        for (let key in res) {
          findNest = res[key].list.find((nest) => {
            return nest.nest_code == that.nestInfo.nest_code;
          });
          if (findNest) {
            break;
          }
        }
        // console.log("findNest", findNest);
        if (findNest) {
          that.weatherInfo = findNest.weather;
        }
      });
    },
    removeBus() {
      this.$bus.off("nestWeather");
    },
    enterNestInfo() {
      this.$bus.emit("openNest", [this.nestInfo, this.isFlying]);
      this.$bus.emit("bottomButtonShow", false);

      if (this.rtcClient) {
        this.leaveClient();
        this.rtcClient = null;
      }
    },
    showShareForm() {
      this.$emit("showShareForm");
    },
    // 通过url 生成id
    geneIdByUrl() {
      if (!this.videoUrl) return;
      const tempArr = this.videoUrl.split("/").reverse();
      this.canvasId = "id" + tempArr[0].split(".")[0];
      return this.canvasId;
    },
    releasePlayer() {
      console.log(this.playerType);
      if (this.playerType === 1) {
        if (!this.player) return;
        console.log("销毁七牛播放器" + this.playerType);
        this.player.release();
      } else if (this.playerType === 2) {
        if (!this.player) return;
        try {
          this.player.pause();
        } catch (e) {
          console.log(e);
        }
        console.log("销毁阿里播放器");
        this.player.dispose();
      } else if (this.playerType === 3) {
        console.log("销毁声网播放器");
        this.leaveClient();
        this.rtcClient = null;
      } else if (this.playerType === 4) {
        if (!this.$options.jessibuca) return;
        console.log("releasePlayer JPro播放器");
        this.$options.jessibuca.destroy();
        this.$options.jessibuca = null;
      }
      this.player = null;
      this.playerType = 0;
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
    },
    initPlayer() {
      console.log("initPlayer url:", this.videoUrl);
      var uurl = this.videoUrl;
      // var uurl = "channel=test"
      if (uurl.indexOf("channel") != -1) {
        var value = uurl.split("=")[1];
        djiAgoraToken({
          channel: value,
        }).then((res) => {
          if (res.data) {
            this.rtcToken = res.data;
            this.rtcChannel = value;
            this.initAgoraPlayer();
          } else {
            console.log("rtc token fail");
          }
        });
      } else {
        // this.initAliPlayer();
        this.initJProPlayer();
      }
    },
    async joinClient(options) {
      let clientRoleOptions = {
        // Set latency level to low latency
        level: 1,
      };
      this.rtcClient.setClientRole(options.role, clientRoleOptions);
      console.log(options);
      await this.rtcClient.join(
        options.appId,
        options.channel,
        options.token,
        options.uid
      );
    },
    leaveClient() {
      console.log("清除声网播放器");
      this.rtcClient.remoteUsers.forEach((user) => {
        // Destroy the dynamically created DIV containers.
        const playerContainer = document.getElementById(user.uid);
        playerContainer && playerContainer.remove();
      });

      // Leave the channel.
      this.rtcClient.leave();
    },
    async initAgoraPlayer() {
      if (this.rtcClient) {
        this.leaveClient();
        this.rtcClient = null;
      }
      console.log("声网播放");
      // 消除ali播放器给div添加上prism-player class导致video偏移
      document.getElementById(this.canvasId).setAttribute("class", "");
      this.playerType = 3;
      let options = {
        // Pass your app ID here.
        appId: "7495598a7a2c4b5b9b70460b529b5132",
        // Set the channel name.
        channel: this.rtcChannel,
        // Set the user role in the channel.
        role: "audience",
        // Use a temp token
        token: this.rtcToken,
        // Uid
        uid: this.$store.getters.userInfo.user_id,
      };

      this.rtcClient = AgoraRTC.createClient({
        mode: "live",
        codec: "vp8",
      });
      this.joinClient(options);

      this.rtcClient.on("user-published", async (user, mediaType) => {
        // Subscribe to a remote user.
        await this.rtcClient.subscribe(user, mediaType);
        console.log("subscribe success");
        console.log(mediaType);
        // If the subscribed track is video.
        if (mediaType === "video") {
          // Get `RemoteVideoTrack` in the `user` object.
          const remoteVideoTrack = user.videoTrack;
          // Dynamically create a container in the form of a DIV element for playing the remote video track.
          const remotePlayerContainer = document.createElement("div");
          // Specify the ID of the DIV container. You can use the `uid` of the remote user.
          remotePlayerContainer.id = user.uid.toString();
          remotePlayerContainer.style.width = "100%";
          remotePlayerContainer.style.height = "calc(100% - 10px)";
          remotePlayerContainer.style.position = "relative";
          document.getElementById(this.canvasId).append(remotePlayerContainer);
          remoteVideoTrack.play(remotePlayerContainer);
        }
      });

      this.rtcClient.on("user-unpublished", (user) => {
        // Get the dynamically created DIV container.
        const remotePlayerContainer = document.getElementById(user.uid);
        // Destroy the container.
        remotePlayerContainer.remove();
      });
    },
    initAliPlayer() {
      if (this.player) {
        this.releasePlayer();
      }
      const that = this;
      this.player = new Aliplayer({
        id: this.canvasId,
        source: this.videoUrl, // 播放地址，可以是第三方直播地址，或阿里云直播服务中的拉流地址。
        isLive: true, // 是否为直播播放。
        autoplay: true,
        preload: true,
        useH5Prism: true,
        showBuffer: false,
        controlBarVisibility: "never",
        flvFrameChasing: true,
      });
      this.playerType = 2;
    },
    initJProPlayer() {
      if (this.player) {
        this.releasePlayer();
      }
      this.is_offline_2 = false;
      console.log("JPro播放器");
      this.playerType = 4;
      var options = {};
      this.$options.jessibuca = new window.JessibucaPro(
        Object.assign(
          {
            decoder: "/js/jessibuca/decoder-pro.js",
            container: document.getElementById(this.canvasId),
            videoBuffer: 0.2, // 缓存时长
            isResize: false,
            useWCS: true,
            useMSE: false,
            useSIMD: false,
            text: "",
            loadingText: "疯狂加载中...",
            debug: false,
            supportDblclickFullscreen: true,
            showBandwidth: false, // 显示网速
            operateBtns: {
              fullscreen: false,
              screenshot: false,
              play: false,
              audio: false,
            },
            forceNoOffscreen: false,
            isNotMute: true,
            timeout: 10,
            hasAudio: false,
          },
          options
        )
      );
      var _this = this;
      this.$options.jessibuca.on("load", function () {
        console.log("on load");
      });
      _this.$options.jessibuca.play(_this.videoUrl);

      // 设置定时器，在半小时后停止播放
      this.timeoutId = setTimeout(() => {
        this.releasePlayer();
        this.is_offline_2 = true;
      }, 1800 * 1000);
    },
    getWindLevel(val) {
      const number = parseInt(val);
      if (number > -1) {
        return CNWord[number];
      } else {
        return "N";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .prism-big-play-btn {
  display: none !important;
}

::v-deep .prism-ErrorMessage {
  display: none !important;
}

.nest_item {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  //pointer-events: none;

  .nest_video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;

    ::v-deep video {
      object-fit: fill !important;
    }
  }

  .nest_weather {
    z-index: 1;
    max-width: 120px;
    min-width: 70px;
    background: rgba(5, 29, 40, 0.5);
    padding: vh(10) 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    position: absolute;
    bottom: 0;
    left: 0;
    margin-bottom: vh(30);

    .weather_item {
      display: grid;
      grid-template-columns: auto 1fr;
      grid-template-rows: 1.5fr 1fr;

      column-gap: 5px;

      .weather_icon {
        grid-row-start: 1;
        grid-row-end: 3;
        height: vh(35);
        width: vh(35);
      }

      .weather_key {
        text-align: start;
        line-height: 100%;
        font-size: 12px;
        color: lightgray;
      }

      .weather_value {
        font-size: 14px;
        text-align: start;
        line-height: 100%;
      }
    }
  }

  .bottom_info {
    z-index: 1;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    line-height: vh(30);
    height: vh(30);
    max-height: vh(30);
    overflow: hidden;
    background: rgba(5, 29, 40, 0.5);
    text-align: left;
    padding-left: 15px;
    padding-right: 5px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;

    .title {
      flex: 1;
    }

    .btn_enter {
      cursor: pointer;
      color: #1cc1ff;
      margin-left: 6px;
      width: 20px;
      height: 20px;
    }
  }

  .quality-menu {
    border: none;
    border-radius: 0;
    background-color: grey;
    padding: 0;

    .quality-item {
      color: white;
      background-color: rgba(3, 17, 24, 0.6);

      &:hover {
        color: white;
        background-color: rgba(3, 17, 24, 0.8);
      }

      &:active {
        color: white;
      }
    }

    .selected-item {
      background-color: rgb(12, 65, 112);
      color: white;
    }
  }
}

.el-dropdown-link {
  font-size: 12px;
  color: #1cc1ff;
  border: #1cc1ff 1px solid;
  padding: 1px 4px;
  border-radius: 4px;
  cursor: pointer;

  ::v-deep .el-dropdown-menu {
    background-color: red;
  }
}
</style>
